<?php

namespace app\common\command;
use app\api\model\wanlshop\LangCopy;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Throwable;

class Language extends Command
{
    public $redis = null;
    public function __construct($name = null)
    {
        $this->redis = \addons\wanlshop\library\WanlSdk\Common::redis();
        parent::__construct($name);
    }

    protected function configure()
    {
        $this->setName('language')->setDescription('Redis语言包备份');
    }

    protected function execute(Input $input, Output $output)
    {

        $this->categoryAdd('category');
        $this->categoryAdd('goods');
    }
    /**
     * 备份数据备份
     * @return void
     *
     */
    public function categoryAdd($redisKey){
        $result = $this->redis->scan($iterator, $redisKey.':*',999999);
        Db::startTrans();
        try {
            $model = new LangCopy();
            $num = 0;
            foreach ($result as $k=>$v){
                $arr = explode(":", $v);
                $arrTwo = explode('-', $arr[1]);
                $langType = $arrTwo[0];
                $langName = $arrTwo[1];
                $lang = $this->redis->get($v);
                $info = $model->where(['lang_db'=>$redisKey,'lang_type'=>$langType,'lang_name'=>$langName,'lang'=>$lang])->find();
                if(!$info){
                    $model = new LangCopy();
                    $model->lang_db   = $redisKey;
                    $model->lang_type = $langType;
                    $model->lang_name = $langName;
                    $model->lang = $lang;
                    $model->createtime = date('Y-m-d H:i:s');
                    $r =  $model->save();
                    if($r){
                        $num ++;
                    }
                }
            }
            Db::commit();
            if(!$num){
                echo $redisKey.'今日无备份';
            }else{
                echo $redisKey.'成功'.$num.'条';
            }
        } catch (ValidateException|PDOException|Throwable $e) {
            Db::rollback();
            echo '分类入库报错啦--'.$e->getMessage();
        }
    }
}
